package com.zyt.test;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Map;
import java.util.Set;

@WebServlet("/demo1")
public class RequestDemo1 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 处理中文编码问题
        req.setCharacterEncoding("utf-8");

        // ========请求行 GET /path HTTP/1.1========
        // 获取请求方法：GET、POST
        String method = req.getMethod();
        System.out.println("method = " + method);
        // 获取URI：/15_Request_war_exploded/demo1
        String uri = req.getRequestURI();
        System.out.println("uri = " + uri);
        // 获取ContextPath /15_Request_war_exploded
        String contextPath = req.getContextPath();
        System.out.println("contextPath = " + contextPath);
        // 获取URL：http://localhost:8080/15_Request_war_exploded/demo1
        String url = req.getRequestURL().toString();
        System.out.println("url = " + url);
        // 获取请求参数
        String queryString = req.getQueryString();
        System.out.println("queryString = " + queryString);
        // 获取PROTOCOL：HTTP/1.1
        String protocol = req.getProtocol();
        System.out.println("protocol = " + protocol);

        // 获取IP
        String ip = req.getRemoteAddr();
        System.out.println("ip = " + ip);
        // 获取RemoteHost：
        String rHost = req.getRemoteHost();
        System.out.println("rHost = " + rHost);
        // 获取RemotePort
        int rPort = req.getRemotePort();
        System.out.println("rPort = " + rPort);

        // =======请求头========
        // 获取Header参数
        String userAgent = req.getHeader("user-agent");
        System.out.println("userAgent = " + userAgent);

        // 获取所有的Header
        Enumeration<String> headerNames = req.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            String headerValue = req.getHeader(headerName);
            System.out.println(headerName + "=>" + headerValue);
        }

        // ========请求体========
        // 获取参数
        Map<String, String[]> parameterMap = req.getParameterMap();
        System.out.println("parameterMap = " + parameterMap);
        
        Set<String> keys = parameterMap.keySet();
        for (String key: keys) {
            String value = req.getParameter(key);
            System.out.println(key + "=>" + value);
        }

        // 获取Attribute域对象
        String msg = (String) req.getAttribute("msg");
        System.out.println("msg = " + msg);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
